package com.example.springlearn.controller;

import com.example.springlearn.bean.UserInfo;
import com.example.springlearn.service.UserService;
import com.example.springlearn.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Resource
    UserService userService;

    @ResponseBody
    @PostMapping("/register")
    public String register(UserInfo userInfo) {
        userService.insert(userInfo);
        return userInfo.getUid().toString();
    }

    @PostMapping("/login")
    public String login(UserInfo userInfo, HttpServletResponse resp) {

        log.info("{}", userInfo);

        userInfo = userService.searchUserInfo(userInfo);
        if (userInfo != null) {
            resp.addCookie(CookieUtil.newAllPathCookie("uid", userInfo.getUid().toString()));
            resp.addCookie(CookieUtil.newAllPathCookie("username", userInfo.getUsername()));
            return "redirect:/home/space";
        } else {
            return "redirect:/";
        }
    }

}
